07. Reflection API

Reflection API

In this lesson, you will learn how to inspect Java programs using the reflection API in the java.lang.reflect package.

ND079 JPND C2 L04 A07 Reflection API

Reflection API

Every class, interface, and type (including primitive types) has a corresponding Class object that accesses metadata about that type.

Class objects are the main entry point into Java's Reflection API.

Obtaining Class Objects

There are many ways to get Class objects:

  • Call getClass() on an object:

    Class c = "Hello world!".getClass();

  • Use .class to create a class literal:

    Class c = String.class;
    Class c = int[].class;

  • Create classes dynamically using Class.forName():

    Class c = Class.forName("java.lang.String");

Once you have a Class object, you can start using reflection with the Class API! Click the link to familiarize yourself with the methods available on classes.

How can you get a Class object?

SOLUTION:
  • Invoke `getClass()` on an object.
  • Add `.class` to a type name to create a class literal.
  • Call `Class.forName(String)`

What is the class literal for the byte type?

SOLUTION: `byte.class`

Working with Methods

Using the Class API, you can also obtain Method objects.

Methods have some smiliar functionality as Classes, such as finding annotations and listing qualifiers, but methods can also be invoked by calling Method.invoke().

You should click the link to familiarize yourself with this API.

If you have a Method object, how can you call the method it references?

SOLUTION: Call the `invoke()` method

What does the following code print?

Method m = "Atticus".getClass().getMethod("toLowerCase");
System.out.println(m.invoke("Finch"));
SOLUTION: The code prints `finch`

What does the following code print?

Method m = String.class.getMethod("compareTo");
System.out.println(m.invoke("A", "B"));
SOLUTION: The code throws an exception.